<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/10/26
 * Time: 5:39 PM
 */

namespace App\HttpController\Api\VersionOne;

use App\Logic\ActivityLogic;
use App\Logic\CouponsLogic;
use App\Logic\SignLogic;
use App\Model\ActivityApplyModel;
use App\Model\ActivityModel;
use App\Model\ActivitySignModel;
use App\Model\CouponsUserModel;
use App\Model\RewardOrderModel;
use App\Model\UserMoneyModel;
use App\Utility\CommonTool;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\AnnotationTag\Param;
use EasySwoole\HttpAnnotation\AnnotationTag\Method;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Pool\Exception\PoolEmpty;
use EasySwoole\Pool\Manager;
use Throwable;

class Activity extends VersionBase
{
    protected $whiteList = ['read', 'rank'];

    /**
     * 显示活动详情页接口
     * @Method(allow={POST})
     * @Param(name="user_id", alias="用户ID", required="", integer="", min="1", notEmpty="不能为空")
     * @Param(name="activity_id", alias="赛事ID", required="", integer="", min="1", notEmpty="不能为空")
     * @throws Exception
     * @throws PoolEmpty
     * @throws Throwable
     */
    public function read()
    {
        $userId = $this->input('user_id', 0);
        $activityId = $this->input('activity_id', 1);

        $activity = DbManager::getInstance()->invoke(function ($client) use ($activityId) {
            return ActivityModel::invoke($client)->where('id', $activityId)->get();
        });
        if (!$activity) {
            $this->writeJson(Status::CODE_BAD_REQUEST, [], "该活动不存在");
            return false;
        }

        /* ----------------------判断是否已经截止报名 开始---------------------- */
        if (time() > strtotime($activity->expiration_datetime)) {
            $isExpiration = 1;
        } else {
            $isExpiration = 0;
        }
        /* ----------------------判断是否已经截止报名 结束---------------------- */

        /* ----------------------tab标题栏 开始---------------------- */
        $tabs = [];
        $list = DbManager::getInstance()->invoke(function ($client) use ($activity) {
            $activityModel = ActivityModel::invoke($client);
            $activityModel->where('btype_id', $activity->btype_id);
            $activityModel->where('name', $activity->name);
            $activityModel->where('game_type', $activity->game_type);
            $activityModel->order('days_held', 'asc');
            $activityModel->order('bet_amount', 'asc');
            return $activityModel->all();
        });

        foreach ($list as $key => $value) {
            $tabs[$key]['id'] = strval($value->id);
            $tabs[$key]['name'] = strval(CommonTool::getTypeName($value->stype_id, 2));
            $tabs[$key]['status'] = ($value->id == $activityId) ? '1' : '0';
        }
        /* ----------------------tab标题栏 结束---------------------- */

        $redis = Manager::getInstance()->get('redis')->getObj();
        if ($redis->exists('list_' . $activityId . '_' . date('YmdHis'))) {
            $listActivitySign = intval($redis->lLen('list_' . $activityId . '_' . date('YmdHis')));
        } else {
            $listActivitySign = 0;
        }
        if ($redis->exists('set_join_' . $activityId)) {
            $setJoinActivity = intval($redis->sCard('set_join_' . $activityId));
        } else {
            $setJoinActivity = 0;
        }
        Manager::getInstance()->get('redis')->recycleObj($redis);
        /* ----------------------挑战失败开奖前，XXX人 开始---------------------- */
        if (time() >= strtotime($activity->end_date . ' ' . $activity->end_time)) {
            $successCount = $listActivitySign;
        } else {
            $successCount = 0;
        }
        /* ----------------------挑战失败开奖前，XXX人 结束---------------------- */

        /* ----------------------今日共有XXX人打卡 开始---------------------- */
        if (time() >= strtotime(date('Y-m-d' . $activity->end_time))) {
            $todayCount = $listActivitySign;
        } else {
            $todayCount = 0;
        }
        /* ----------------------今日共有XXX人打卡 结束---------------------- */

        $isApply = 0;
        $isSign = 0;
        $hadSign = 0;
        $isOver = 0;
        $reward = 0.00;
        if (intval($userId) > 0) {
            // 查询该用户是否报名该赛事
            $apply = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId) {
                $activityApplyModel = ActivityApplyModel::invoke($client);
                $activityApplyModel->changeTableName($userId);
                $activityApplyModel->where('user_id', $userId);
                $activityApplyModel->where('activity_id', $activityId);
                return $activityApplyModel->get();
            });
            if (!$apply) {
                $isApply = 0;
            } else {
                $isApply = 1;
                $hadSign = $apply->sign_time;

                if ($apply->sign_time == $apply->target_time && $apply->status == 0) {
                    $isOver = 4; // 打了卡，等待开奖
                } else {
                    switch ($apply->status) {
                        case 0 : // 待完成的
                            $todayEndTimeStamp = strtotime(date('Y-m-d ' . $activity->end_time)); // 获取最后签到时间戳
                            $needSignNumber = (strtotime(date('Y-m-d')) - strtotime($activity->start_date)) / 86400; // 获取应该签到的日期(今天尚未打卡)
                            if ($todayEndTimeStamp < time()) {
                                //超过打卡时间,应该打卡
                                $needSignNumber = $needSignNumber + 1;
                            }
                            if ($needSignNumber > $apply->sign_time) {
                                $isOver = 2; // 参与失败
                            } else {
                                $isOver = 0; // 还没有打卡
                            }
                            break;
                        case 1 : // 已完成已开奖
                            $isOver = 1; // 打卡成功
                            break;
                        case 2 : // 参与失败的
                            $isOver = 2; // 参与失败
                            break;
                    }
                }
            }

            // 查询该用户是否当天已经打卡
            $sign = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId) {
                $activitySignModel = ActivitySignModel::invoke($client);
                $activitySignModel->changeTableName($userId);
                $activitySignModel->where('user_id', $userId);
                $activitySignModel->where('activity_id', $activityId);
                $activitySignModel->where('LEFT(sign_datetime, 10)', date('Y-m-d'));
                return $activitySignModel->count();
            });

            if (!$sign) {
                $isSign = 0;
            } else {
                $isSign = 1;
            }

            if ($activity->status == 2 && $isApply == 1 && $apply->sign_time == $apply->target_time) {
                // 判断活动是否已经下架 且 参与活动 且 打卡挑战成功
                $reward = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId) {
                    $rewardOrderModel = RewardOrderModel::invoke($client);
                    $rewardOrderModel->changeTableName($userId);
                    $rewardOrderModel->where('user_id', $userId);
                    $rewardOrderModel->where('activity_id', $activityId);
                    return $rewardOrderModel->val('reward');
                });
            }
        }

        /* ----------------------判断是否可以打卡和倒计时 开始---------------------- */
        if (time() < strtotime($activity->start_date . ' ' . $activity->start_time) || time() > strtotime($activity->end_date . ' ' . $activity->end_time)) {
            // 当前时间小于赛事开始时间 或 当前时间大于赛事结束时间，不让打卡
            $status = 0;
            if (time() < strtotime($activity->start_date . ' ' . $activity->start_time)) {
                $laveTime = strtotime($activity->start_date . ' ' . $activity->start_time) - time();
            } else {
                $laveTime = 86400 * 365 * 10;
            }
        } else {
            if (time() < strtotime(date('Y-m-d ' . $activity->start_time)) || time() > strtotime(date('Y-m-d ' . $activity->end_time))) {
                //当前时间不在打卡时间段以内的话，不让打卡
                $status = 0;
                if (time() < strtotime(date('Y-m-d ' . $activity->start_time))) {
                    $laveTime = strtotime(date('Y-m-d ' . $activity->start_time)) - time();
                } else {
                    $laveTime = strtotime(date('Y-m-d ' . $activity->start_time)) + 86400 - time();
                }
            } else {
                $status = 1;
                if ($isSign == 1) {
                    $laveTime = strtotime(date('Y-m-d ' . $activity->start_time)) + 86400 - time();
                } else {
                    $laveTime = 0;
                }
            }
        }
        /* ----------------------判断是否可以打卡和倒计时 结束---------------------- */

        // 当前日期是否最后一天
        if (date('Y-m-d') == $activity->end_date) {
            $isLastDay = 1;
        } else {
            $isLastDay = 0;
        }

        // 没有报名 且 已经截止
        // 有报名 且 该用户是否已经结束比赛已完成 或 参与失败
        if (($isApply == 0 && $isExpiration == 1) || ($isApply == 1 && $isOver == 1 && $activity->status == 2) || ($isApply == 1 && $isOver == 2)) {
            $nextActivity = DbManager::getInstance()->invoke(function ($client) use ($activity) {
                $activityModel = ActivityModel::invoke($client);
                $activityModel->where('stype', $activity->stype_id);
                $activityModel->where('is_add', $activity->is_add);
                $activityModel->where('status', 1);
                $activityModel->order('id', 'desc');
                $activityModel->limit(1);
                return $activityModel->val('id');
            });
        } else {
            $nextActivity = 0;
        }

        /* ----------------------末位淘汰赛 开始---------------------- */
        $outNum = 0;
        $outRate = 5;
        $outRateRule = [
            '27' => 3,
            '28' => 4,
            '29' => 5,
        ];
        foreach ($outRateRule as $k => $v) {
            if ($k == $activity->stype) {
                $outRate = $v;
            }
        }
        if ($activity->game_type == 2) {
            // 末位淘汰赛计算淘汰人数
            if (time() >= strtotime($activity->expiration_datetime)) {
                $applyCount = $setJoinActivity;
                $outNum = floor($applyCount * $outRate / 100);
                if ($outNum == 0) {
                    $outNum = 1;
                }
            }
        }
        /* ----------------------末位淘汰赛 结束---------------------- */

        $result = [
            'title' => strval(CommonTool::getTypeName($activity->btype_id, 1) . ' - ' . date('md', strtotime($activity->name))) . '期', // 标题
            'game_date' => (($activity->start_date == $activity->end_date) ? date('m-d', strtotime($activity->start_date)) : date('m-d', strtotime($activity->start_date)) . ' - ' . date('m-d', strtotime($activity->end_date))), // 赛事举行日期段
            'game_time' => strval(date('H:i', strtotime(date('Y-m-d ' . $activity->start_time))) . ' - ' . date('H:i', strtotime(date('Y-m-d ' . $activity->end_time)))), // 赛事举行时间段
            'all_reward' => strval($activity->all_reward), // 当前实时奖金
            'all_enrollment' => strval($activity->all_enrollment), // 当前实时报名人数
            'expiration_datetime' => strval($activity->expiration_datetime), // 截止报名时间日期
            'is_login' => intval($userId) > 0 ? '1' : '0', // 是否登录 1.有登录 0.没有登录
            'is_normal' => (intval($activity->is_add) == 1 && intval($activity->days_held) > 1) ? '1' : '2', // 是否普通版 1.普通版 2.高级版
            'is_expiration' => strval($isExpiration), // 是否为截止状态 1.已经截止 0.没有
            'is_apply' => strval($isApply), // 是否已经参与赛事 1.已经参加 0.未参加
            'is_sign' => strval($isSign), // 是否已经签到赛事 1.已经签到 0.未签到
            'status' => strval($status), // 状态 0.不能打卡 1.可以打卡
            'lave_time' => strval($laveTime), // 剩余时长
            'tabs' => $tabs, // tab标题栏
            'next_activity' => strval($nextActivity), // 下场活动ID
            'is_over' => strval($isOver), // 待开奖标识 0.未结束 1.结束
            'is_last_day' => strval($isLastDay), // 是否最后一天 1.是 0.否
            'detail_style' => strval($activity->detail_style), // 详情页样式
            'activity_status' => $activity->status == 1 ? '1' : '2', // 活动是否派奖 1.没有派奖 2.已经派奖
            'reward' => $reward > 0 ? strval($reward) : '0.00', // 活动奖金
            'had_sign' => strval($hadSign), // 已经打卡xxx天
            'success_count' => strval($successCount), // 挑战失败开奖前，XXX人
            'today_count' => strval($todayCount), // 今日共有XXX人打卡
            'game_type' => intval($activity->game_type), // 游戏类型
            'out_rate' => intval($outRate), // 淘汰率
            'out_num' => intval($outNum), // 淘汰人
        ];

        $this->writeJson(Status::CODE_OK, $result, "签到成功");
        return true;
    }

    /**
     * 显示赛事活动支付页面接口
     * @Method(allow={POST})
     * @Param(name="user_id", alias="用户ID", required="", integer="", min="1", notEmpty="不能为空")
     * @Param(name="activity_id", alias="赛事ID", required="", integer="", min="1", notEmpty="不能为空")
     * @throws Exception
     * @throws PoolEmpty
     * @throws Throwable
     */
    public function apply()
    {
        $userId = $this->input('user_id', 0);
        $activityId = $this->input('activity_id', 1);

        $activity = DbManager::getInstance()->invoke(function ($client) use ($activityId) {
            return ActivityModel::invoke($client)->where('id', $activityId)->where('status', 1)->get();
        });
        if (!$activity) {
            $this->writeJson(Status::CODE_BAD_REQUEST, [], "该活动不存在");
            return false;
        }

        // 当前时间大于赛事报名时间，不让报名
        if (time() > strtotime($activity->expiration_datetime)) {
            $this->writeJson(Status::CODE_BAD_REQUEST, [], "赛事已经报名截止");
            return false;
        }

        $allConsumeType = CommonTool::getAllConsumeMap();

        $default = '3'; // 默认选项
        $balance = 0.00;
        $coupons = [];
        $multiple = [];
        if (intval($userId) > 0) {
            // 查询该用户是否报名该赛事
            $userMoney = DbManager::getInstance()->invoke(function ($client) use ($userId) {
                return UserMoneyModel::invoke($client)->where('user_id', $userId)->get();
            });
            if (!$userMoney) {
                $balance = floatval($userMoney->balance);
            }

            $activityApply = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId) {
                return ActivityApplyModel::invoke($client)->changeTableName($userId)->where('user_id', $userId)->where('activity_id', $activityId)->get();
            });
            if ($activityApply) {
                $default = '1';
            }

            // 查询该用户是否优惠券
            try {
                $temp = CouponsLogic::userCouponsList(['userId' => $userId, 'status' => 1, 'page' => 1]);
            } catch (Exception $e) {
                $temp = [];
            } catch (PoolEmpty $e) {
                $temp = [];
            } catch (Throwable $e) {
                $temp = [];
            }

            if (count($temp)) {
                foreach ($temp as $k => $v) {
                    $coupons[$k] = $v;
                    if ($v['is_condition'] == 1 && $v['btype_id'] == $activity->btype_id && $v['stype'] == $activity->stype_id) {
                        $coupons[$k]['status'] = 1;
                    } elseif ($v['is_condition'] == 2) {
                        $coupons[$k]['status'] = 1;
                    } else {
                        $coupons[$k]['status'] = 0;
                    }
                    $coupons[$k]['target_money'] = strval(intval($v['target_money']));
                    $coupons[$k]['offer_money'] = strval(intval($v['offer_money']));
                }

                if ($activityApply) {
                    foreach ($coupons as $k => $v) {
                        $coupons[$k]['status'] = 0;
                    }
                }
            } else {
                $coupons = [];
            }
        }

        if ($activity->is_add == 1) {
            foreach ($allConsumeType as $key => $value) {
                // 用户有登录 且 举行天数为1天 且 默认选项为第一个
                if (intval($userId) > 0 && $activity->days_held == 1 && $default == 1) {
                    continue;
                }
                // 用户有登录 且 举行天数为1天 且 倍数大于5 且 默认选项为第三个
                if (intval($userId) > 0 && $activity->days_held == 1 && (intval($value['multiple']) > 5) && $default == 3) {
                    continue;
                }
                $multiple[$key]['name'] = $value['name'];
                $multiple[$key]['money'] = strval(intval($value['multiple']) * floatval($activity->bet_amount));
            }
        }

        $result = [
            'balance' => strval($balance), // 用户余额
            'bet_amount' => floatval($activity->bet_amount), // 投注金额
            'multiple' => $multiple, // 倍数列表
            'coupons' => $coupons, // 红包列表
            'default_multiple' => $default, // 默认倍数
        ];

        $this->writeJson(Status::CODE_OK, $result, "success");
        return true;
    }

    /**
     * 签到接口
     * @Method(allow={POST})
     * @Param(name="user_id", alias="用户ID", required="", integer="", min="1", notEmpty="不能为空")
     * @Param(name="activity_id", alias="赛事ID", required="", integer="", min="1", notEmpty="不能为空")
     * @return bool
     * @throws Throwable
     */
    public function sign()
    {
        $userId = $this->input('user_id', 0);
        $activityId = $this->input('activity_id', 1);

        /* 加锁,防止用户多次提交 */
        $lockRes = CommonTool::redisLock('sign_' . $userId . '_' . $activityId);
        if (!$lockRes) {
            return $this->writeJson(Status::CODE_BAD_REQUEST, [], '请勿重复请求~');
        }

        try {
            $res = SignLogic::addUserSignHandle($userId, $activityId);
        } catch (Exception $e) {
            $res = [
                "code" => Status::CODE_BAD_GATEWAY,
                "result" => [],
                "msg" => "网络繁忙,请稍后再试"
            ];
        } catch (PoolEmpty $e) {
            $res = [
                "code" => Status::CODE_BAD_GATEWAY,
                "result" => [],
                "msg" => "网络繁忙,请稍后再试"
            ];
        } catch (Throwable $e) {
            $res = [
                "code" => Status::CODE_BAD_GATEWAY,
                "result" => [],
                "msg" => "网络繁忙,请稍后再试"
            ];
        } finally {
            CommonTool::redisUnlock('sign_' . $userId . '_' . $activityId);
        }

        return $this->writeJson($res['code'], $res['result'], $res['msg']);
    }

    /**
     * 下单赛事接口
     * @Method(allow={POST})
     * @Param(name="user_id", alias="用户ID", required="", integer="", min="1", notEmpty="不能为空")
     * @Param(name="activity_id", alias="赛事ID", required="", integer="", min="1", notEmpty="不能为空")
     * @Param(name="coupons_id", alias="优惠券ID", integer="", min="0", notEmpty="不能为空")
     * @Param(name="pay_type", alias="支付类型", required="", integer="", between="1,2,3",, min="1", notEmpty="不能为空")
     * pay_type 1:微信，2:支付宝，3:余额支付
     * @Param(name="money", alias="金额", required="", money="", min="1.00", notEmpty="不能为空")
     * @throws Exception
     * @throws PoolEmpty
     * @throws Throwable
     */
    public function buy()
    {
        $userId = $this->input('userId', 0);
        $activityId = $this->input('activity_id', 0);
        $couponsId = $this->input('coupons_id', 0);
        $payType = $this->input('pay_type', 1);
        $money = $this->input('money', 0.00);

        $activity = DbManager::getInstance()->invoke(function ($client) use ($activityId) {
            return ActivityModel::invoke($client)->findActivity($activityId);
        });
        if ($activity['status'] != 1) {
            $this->writeJson(Status::CODE_BAD_GATEWAY, [], "该活动已下架");
            return false;
        }
        // 当前时间大于赛事报名时间，不让报名
        if (time() > strtotime($activity['expiration_datetime'])) {
            $this->writeJson(Status::CODE_BAD_GATEWAY, [], "赛事已经报名截止");
            return false;
        }

        $offerMoney = 0;
        if ($couponsId > 0) {
            // 查找用户优惠券
            $couponsUserInfo = DbManager::getInstance()->invoke(function ($client) use ($couponsId) {
                $couponsUserModel = CouponsUserModel::invoke($client);
                $field = [
                    'cu.*',
                    'c.name',
                    'c.target_money',
                    'c.offer_money',
                    'c.is_condition',
                    'c.btype',
                    'c.stype',
                    'ct.name as type_name',
                ];
                return $couponsUserModel->field($field)
                    ->where('cu.id', $couponsId)
                    ->alias('cu')
                    ->join('coupons c', 'cu.coupons_id = c.id')
                    ->join('coupons_type ct', 'ct.id = c.type')->get();
            });

            if (!$couponsUserInfo) {
                $this->writeJson(Status::CODE_BAD_GATEWAY, [], "优惠券已过期");
                return false;
            } else {
                $offerMoney = $couponsUserInfo->offer_money;
            }
        }
        if ($money - $offerMoney < 0) {
            $this->writeJson(Status::CODE_BAD_GATEWAY, [], "提交订单异常");
            return false;
        }

        if ($payType == 3) {
            try {
                $res = ActivityLogic::joinActivity($userId, $activityId, $couponsId, $money, ($offerMoney > 0 ? 4 : 2));
            } catch (Exception $e) {
                $res = [];
            } catch (PoolEmpty $e) {
                $res = [];
            } catch (Throwable $e) {
                $res = [];
            }

            return $this->writeJson($res['code'], $res['result'], $res['msg']);
        } else {
            // TODO: 需要做充值处理
            return $this->writeJson(Status::CODE_BAD_GATEWAY, [], "努力开发中");
        }
    }

    /**
     * 赛事排名--排位赛
     * @Method(allow={POST})
     * @Param(name="user_id", alias="用户ID", required="", integer="", min="1", notEmpty="不能为空")
     * @Param(name="activity_id", alias="赛事ID", required="", integer="", min="1", notEmpty="不能为空")
     * @throws Exception
     * @throws PoolEmpty
     * @throws Throwable
     */
    public function rank()
    {
        $userId = $this->input('user_id', 0);
        $activityId = $this->input('activity_id', 1);

        $activity = DbManager::getInstance()->invoke(function ($client) use ($activityId) {
            return ActivityModel::invoke($client)->findActivity($activityId);
        });
        if (!$activity) {
            $this->writeJson(Status::CODE_BAD_GATEWAY, [], "该活动不存在");
            return false;
        }

        $userRate = [];
        $ranking = [];
        $isApply = 0;
        if ($activity['game_type'] == 2) {
            if (intval($userId) > 0) {
                // 查询该用户是否报名该赛事
                $apply = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId) {
                    return ActivityApplyModel::invoke($client)->changeTableName($userId)->where('user_id', $userId)->where('activity_id', $activityId)->get();
                });

                if (!$apply) {
                    $isApply = 0;
                } else {
                    $isApply = 1;
                }
            }

            // 末位淘汰赛计算淘汰人数
            $outRate = 5;
            $outRateRule = [
                '27' => 3,
                '28' => 4,
                '29' => 5,
            ];

            foreach ($outRateRule as $k => $v) {
                if ($k == $activity['stype_id']) {
                    $outRate = $v;
                }
            }
            $applyCount = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId) {
                $activityApplyModel = ActivityApplyModel::invoke($client);
                $activityApplyModel->changeTableName($userId);
                $activityApplyModel->where('activity_id', $activityId);
                return $activityApplyModel->count('user_id');
            });
            $outNum = floor($applyCount * $outRate / 100);
            if ($outNum == 0) {
                $outNum = 1;
            }

            // 没有参赛 且 当前时间 大于 赛事结束时间
            // 有参赛 且 待开奖标识 大于 0
            if (($isApply == 0 && (time() > strtotime($activity['end_date'] . ' ' . $activity['end_time']))) || ($isApply == 1 && (time() > strtotime($activity['start_date'] . ' ' . $activity['start_time'])))) {
                $signed = [];
                $signs = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId) {
                    return ActivitySignModel::invoke($client)
                        ->changeTableName($userId)
                        ->field(['aa.user_id', 'aa.sign_datetime', 'u.nick_name', 'u.headimg_url'])
                        ->alias('aa')
                        ->join('bee_user u', 'aa.user_id = u.id')
                        ->where('aa.activity_id', $activityId)
                        ->where('aa.sign_datetime', date('Y-m-d H:i:s'), '<=')
                        ->order('aa.sign_datetime', 'asc')
                        ->order('aa.id', 'asc')
                        ->all();
                });

                if ($signs) {
                    foreach ($signs as $k => $v) {
                        $ranking[$k] = $v->toArray();
                        $temp = $k + 1;
                        if ($temp <= ($applyCount - $outNum)) {
                            $ranking[$k]['status'] = 1;
                        } else {
                            $ranking[$k]['status'] = 0;
                        }
                        $ranking[$k]['sign_datetime'] = date('H:i:s', strtotime($v->sign_datetime));
                        $ranking[$k]['number'] = $temp;
                        $signed[$k] = $v->user_id;
                    }
                }

                $noSigns = DbManager::getInstance()->invoke(function ($client) use ($userId, $activityId, $signed) {
                    return ActivityApplyModel::invoke($client)
                        ->changeTableName($userId)
                        ->alias('aa')
                        ->field(['aa.user_id', 'u.nick_name', 'u.headimg_url'])
                        ->join('bee_user u', 'aa.user_id = u.id')
                        ->where('aa.user_id', $signed, 'not in')
                        ->all();
                });

                $rankCount = count($ranking);

                if ($noSigns) {
                    foreach ($noSigns as $k => $v) {
                        $temp = [];
                        $temp['user_id'] = $v->user_id;
                        $temp['sign_datetime'] = '未打卡';
                        $temp['nick_name'] = $v->nick_name;
                        $temp['headimg_url'] = $v->headimg_url;
                        $temp['status'] = 0;
                        $temp['number'] = intval($rankCount + $k + 1);
                        $ranking[intval($rankCount + $k)] = $temp;
                    }
                }

                foreach ($ranking as $k => $v) {
                    if (intval($userId) > 0 && $v['user_id'] == $userId) {
                        $userRate = $v;
                    }
                }
            } else {
                $ranking = [];
            }
        }

        $result = [
            'rank' => $ranking, // 排名
            'user_rate' => $userRate, // 当前用排名信息
        ];
        return $this->writeJson(Status::CODE_OK, $result, "success");
    }
}